#region License

// Dimebrain TweetSharp
// (www.dimebrain.com)
// 
// The MIT License
// 
// Copyright (c) 2009 Dimebrain
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// 

#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Dimebrain.TweetSharp.Core.Extensions;

namespace Dimebrain.TweetSharp.Core.Web
{
    /// <summary>
    /// A web query instance that tracks its <see cref="WebRequest"/>
    /// and <see cref="WebResponse" /> pair in order to inform a consumer.
    /// </summary>
    public class WebQueryClient : 
        WebClient, 
        IWebQueryClient
    {
        public WebResponse Response { get; private set; }
        public WebRequest Request { get; private set; }

        public bool UseCompression { get; set; }
        public string ProxyValue { get; set; }

        private readonly IDictionary<string, string> _headers;
        public WebParameterCollection Parameters { get; private set; }
        public string UserAgent { get; private set; }
        
        public WebQueryClient(IDictionary<string, string> headers, WebParameterCollection parameters, string userAgent)
        {
            _headers = headers;
            Parameters = parameters;
            UserAgent = userAgent;
        }

        public WebRequest GetWebRequestShim(Uri address)
        {
            return GetWebRequest(address);
        }
        
#if !SILVERLIGHT
        public WebResponse GetWebResponseShim(WebRequest request)
        {
            return GetWebResponse(request);
        }
#endif
        public WebResponse GetWebResponseShim(WebRequest request, IAsyncResult result)
        {
            return GetWebResponse(request, result);
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
#if !Smartphone
            var request = (HttpWebRequest) base.GetWebRequest(address);
#else
            var request = (HttpWebRequest) WebRequest.Create(address);
#endif
            if (_headers != null)
            {
                foreach (var header in _headers)
                {
#if !SILVERLIGHT
                    request.Headers.Add(header.Key, header.Value);
#else
                    request.Headers[header.Key] = header.Value;
#endif

                }
            }

            if (UseCompression)
            {
#if !SILVERLIGHT
                request.AutomaticDecompression = DecompressionMethods.GZip;
#else
                request.Accept = "gzip,deflate";
#endif
            }
            
            if (Credentials != null)
            {
                // NetworkCredentials always makes two trips, even if with PreAuthenticate
                // request.Credentials = Credentials;

                var credentials = (NetworkCredential) Credentials;
                request.Headers["Authorization"] = credentials.ToAuthorizationHeader();
#if !SILVERLIGHT
                // todo consider removing if we're already setting auth explicitly
                request.PreAuthenticate = true; 
#endif
            }

            if (Parameters != null)
            {
                var hasParameters = address.Query.Contains("?");
                foreach (var parameter in Parameters)
                {
                    address.Query.Then(hasParameters ? "&" : "?");
                    address.Query.Then("{0}={1}".FormatWith(parameter.Name, parameter.Value));
                    hasParameters = true;
                }
            }

#if !SILVERLIGHT
            if (!ProxyValue.IsNullOrBlank())
            {
                request.Proxy = new WebProxy(ProxyValue);
                if(Credentials != null)
                {
                    var credentials = (NetworkCredential) Credentials;
                    request.Headers["Proxy-Authorization"] = credentials.ToAuthorizationHeader();
                }
            }
#endif

            if(!UserAgent.IsNullOrBlank())
            {
#if !SILVERLIGHT
                request.UserAgent = UserAgent;
#else
                request.Headers["User-Agent"] = UserAgent;
#endif
            }

            Request = request;
            return request;
        }

#if !SILVERLIGHT
        protected override WebResponse GetWebResponse(WebRequest request)
        {
            try
            {
#if !Smartphone
                var response = base.GetWebResponse(request);
#else
                var response = request.GetResponse();
#endif
                Response = response;
                return response;
            }
            catch(WebException ex)
            {
                return HandleWebException(ex);
            }
        }
#endif

        protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
        {
            try
            {
#if !Smartphone
                var response = base.GetWebResponse(request, result);
#else
                var response = request.GetResponse();
#endif
                Response = response;
                return response;
            }
            catch(WebException ex)
            {
                return HandleWebException(ex);
            }
        }

        private WebResponse HandleWebException(WebException ex)
        {
            if (ex.Response != null && ex.Response is HttpWebResponse)
            {
                Response = ex.Response;
                return ex.Response;
            }

            // not the droids we're looking for
            throw ex;
        }
    }
}